package com.photography.service.impl;

import com.alipay.api.domain.Car;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.common.JwtTokenUtils;
import com.photography.common.Result;
import com.photography.entity.Cart;
import com.photography.entity.Product;
import com.photography.exception.ErrorCode;
import com.photography.mapper.CartMapper;
import com.photography.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.photography.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;
    @Resource
    private ProductService productService;

    private Integer getLoginUserId() {
        return Objects.requireNonNull(JwtTokenUtils.getCurrentUser()).getUserId();
    }

    /**
     * 新增购物车
     *
     * @param cart 购物车信息
     * @return 结果
     */
    @Override
    public Result addToCart(Cart cart) {
        // 参数校验
        if (cart.getUserId() == null) {
            return Result.error("用户ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!cart.getUserId().equals(getLoginUserId())) {
            return Result.error("请使用本人真实id");
        }
        if (cart.getProductId() == null) {
            return Result.error("商品ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
            return Result.error("商品数量必须大于0", ErrorCode.PARAM_ERROR.getCode());
        }

        // 检查商品是否存在
        Product product = productService.getById(cart.getProductId());
        if (product == null) {
            return Result.error("此产品已下架", ErrorCode.DATA_NOT_EXIST.getCode());
        }

        // 检查是否已存在相同商品
        Cart haveCart = cartMapper.findByUserIdAndProductId(cart.getUserId(), cart.getProductId());
        if (haveCart != null) {
            // 如果存在，更新数量
            haveCart.setQuantity(haveCart.getQuantity() + cart.getQuantity());
            this.updateById(haveCart);
            return Result.success("商品数量已更新");
        } else {
            // 如果不存在，新增记录
            cart.setCreateTime(new Date());
            this.save(cart);
            return Result.success("商品已添加到购物车");
        }
    }

    /**
     * 删除购物车记录
     *
     * @param id 购物车id
     * @return 结果
     */
    @Override
    public Result deleteCart(Integer id) {
        if (id == null) {
            return Result.error("id不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        Cart haveCart = this.getById(id);
        if (haveCart == null) {
            return Result.error("此购物车信息不存在", ErrorCode.DATA_NOT_EXIST.getCode());
        }

        if (!haveCart.getUserId().equals(getLoginUserId())) {
            return Result.error("只能删除自己的购物车信息");
        }
        boolean result = this.removeById(id);
        if (result) {
            return Result.success(null, "删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 清空用户购物车
     *
     * @return 结果
     */
    @Override
    public Result clearCart() {

        boolean result = this.remove(new QueryWrapper<Cart>().eq("user_id", getLoginUserId()));
        if (result) {
            return Result.success(null, "清空成功");
        } else {
            return Result.error("清空失败");
        }
    }

    @Override
    public Result updateQuantity(Integer id, Integer quantity) {
        if (id==null){
            return Result.error("id为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (quantity == null) {
            return Result.error("数量为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        Cart updateCart = new Cart();
        updateCart.setId(id);
        updateCart.setQuantity(quantity);
        boolean result = updateById(updateCart);
        if (result) {
            return Result.success(null, "更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 分页查询购物车列表
     *
     * @param page 分页参数
     * @return 结果
     */
    @Override
    public Page<Map<String, Object>> getCartPage(Page<Cart> page) {
        String userRole = JwtTokenUtils.getCurrentRole();
        if (!Objects.equals(userRole, "manager")) {
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cart::getUserId, getLoginUserId());
            Page<Cart> cartPage = page(page, queryWrapper);

            // 将购物车列表转换为Map格式
            List<Map<String, Object>> records = cartPage.getRecords().stream()
                    .map(cart -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("quantity", cart.getQuantity());
                        map.put("id",cart.getId());
                        Product product = productService.getById(cart.getProductId());
                        map.put("productId",product.getProductId());
                        map.put("productName", product.getProductName());
                        map.put("englishName", product.getEnglishName());
                        map.put("imageUrls", product.getImageUrls());
                        map.put("price", product.getPrice());
                        return map;
                    })
                    .collect(Collectors.toList());
            // 创建新的Page对象，包含转换后的记录
            Page<Map<String, Object>> resultPage = new Page<>(cartPage.getCurrent(), cartPage.getSize(), cartPage.getTotal());
            resultPage.setRecords(records);

            return resultPage;
        } else {
            Page<Cart> cartPage = page(page);

            // 将购物车列表转换为Map格式
            List<Map<String, Object>> records = cartPage.getRecords().stream()
                    .map(cart -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("quantity", cart.getQuantity());
                        Product product = productService.getById(cart.getProductId());
                        map.put("productId",product.getProductId());
                        map.put("productName", product.getProductName());
                        map.put("englishName", product.getEnglishName());
                        map.put("imageUrls", product.getImageUrls());
                        map.put("price", product.getPrice());
                        return map;
                    })
                    .collect(Collectors.toList());

            // 创建新的Page对象，包含转换后的记录
            Page<Map<String, Object>> resultPage = new Page<>(cartPage.getCurrent(), cartPage.getSize(), cartPage.getTotal());
            resultPage.setRecords(records);

            return resultPage;
        }
    }

    /**
     * 获取购物车总金额
     *
     * @return 结果
     */
    @Override
    public Result getCartTotalAmount() {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, getLoginUserId());
        List<Cart> cartList = this.list(queryWrapper);

        if (cartList == null || cartList.isEmpty()) {
            return Result.success(0, "购物车为空");
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Cart cart : cartList) {
            Product product = productService.getById(cart.getProductId());
            if (product != null && product.getPrice() != null) {
                // 计算每个商品的总价：数量 * 单价
                BigDecimal itemTotal = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
                totalAmount = totalAmount.add(itemTotal);
            }
        }

        return Result.success(totalAmount, "获取购物车总金额成功");
    }
}
